package com.example.myservlet;

import com.example.anno.RequestMapping;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Enumeration;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/json")
public class JsonServlet extends HttpServlet {
    private final ObjectMapper mapper = new ObjectMapper();

    public static class User {
        public String name;
        public int age;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String body = req.getReader()
                .lines()
                .collect(Collectors.joining());
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            log.info(name + ": " + req.getHeader(name));
        }
        log.info("raw body: " + body);

//        User user = JSON.parseObject(body, User.class);
//        resp.setContentType("application/json;charset=UTF-8");
//        resp.getWriter().printf(JSON.toJSONString(user));
        User user = mapper.readValue(body, User.class);
        resp.setContentType("application/json;charset=UTF-8");
        mapper.writeValue(resp.getOutputStream(), user);   // 原样回显
    }
}